import datetime

from deps.voidsdk.pytoolset.datetime import now
from deps.voidsdk.pytoolset.random import random_string
from .models import ApiAccessToken


def get_api_access_token(user):
    access_token = None
    records = ApiAccessToken.objects.filter(user=user).order_by("-id")
    if records.exists():
        latest_record = records[0]
        if not latest_record.expired:
            access_token = latest_record.access_token

    if not access_token:
        new_record = ApiAccessToken(user=user,
                access_token=random_string(),
                expire_timestamp=now() + datetime.timedelta(days=1))
        new_record.save()
        access_token = new_record.access_token
    return access_token


def get_user_info(user):
    info = {}
    for field in ("id", "sex", "is_supporter", "area_id",
            "height", "weight", "education", "income", "phone", "nickname",
            "avatar", "marital_status", "cover", "statement", "member_level",
            "is_realname"):
        info[field] = getattr(user, field)
    if user.birth_day:
        info["birth_day"] = user.birth_day.strftime("%Y-%m-%d")
        info["age"] = now().year - user.birth_day.year
    else:
        info["birth_day"] = None
        info["age"] = 0
    return info
